<?php
 
namespace Modules\AuthAdmin\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use JWTAuth;
use App\Exceptions\ApiException;
use Modules\AuthAdmin\Models\Admin as AdminModel;
use Modules\AuthAdmin\Models\AuthGroup as AuthGroupModel;
use Modules\AuthAdmin\Models\AuthRule as AuthRuleModel;
class AdminApiAuth
{
    /**
     * Handle an incoming request.
     * php artisan module:make-middleware AdminAuth Admin	
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
		 
		\Config::set('auth.defaults.guard', 'auth_admin');
		\Config::set('jwt.ttl', 60);
		$route_data = $request->route(); 
		$url = str_replace($route_data->getAction()['prefix'] . '/',"",$route_data->uri);
		$url_arr = ['auth/login/login','auth/auth_config/config_info'];
		$response = $next($request);
		$api_key = $request->header('apikey');
		if($api_key != config('authadmin.api_key')){
			throw new ApiException(['code'=>1101,'msg'=>'apikey错误！']);
		}
		if(in_array($url,$url_arr)){
			return $response;
		} 
		try {
            if (! $user = JWTAuth::parseToken()->authenticate()) {  //获取到用户数据，并赋值给$user   'msg' => '用户不存在'
				throw new ApiException(['code'=>1004,'msg'=>'请先登录！']);
            }
		} catch (TokenExpiredException $e) {
			//token已过期
			throw new ApiException(['code'=>1003,'msg'=>'token 过期！']);
        } catch (TokenInvalidException $e) {
			//token无效
			if(!in_array($url,['auth/index/refresh','auth/index/logout'])){
				throw new ApiException(['code'=>1002,'msg'=>'请先登录！']);
			}
        } catch (JWTException $e) {
			//'缺少token'
			throw new ApiException(['code'=>1001,'msg'=>'请先登录！']);
        }
		if(!in_array($url,['auth/index/refresh','auth/index/logout'])){
			if($user['id'] != 1 && $id = AuthRuleModel::where(['href'=>$url])->value('id')){
				$rules = AuthGroupModel::where(['id'=>$user['group_id']])->value('rules');
				if(!in_array($id,explode('|',$rules))){
					throw new ApiException(['code'=>6781,'msg'=>'您没有权限！']);
				} 
			}
		}
		return $response;
    }
}
